package riteh.eventNetwork.client;

import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.View.OnClickListener;

public class ActivityUserEdit extends Activity {
	
	private static final int DATE_DIALOG_ID = 0;
	private EditText editName, editSurname, editEmail, editDate, editPassword, editPasswordRepeat;
	private TextView labelPassword, labelPasswordRepeat;
	private Button btnSave;
	private long userId=0, userInfoId=0;
	private int year,month,day;
    private ImageView image;
    Intent intentResult, intentImage;
    
    private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int tmpYear, int tmpMonth, int tmpDay) {
            year = tmpYear;
            month = tmpMonth;
            day = tmpDay;
            updateDateDisplay();
        }
    };
	
/* ********************** OVERRIDE FUNCTIONS ******************************/

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(C.TAG, "USER EDIT Activity");
		setContentView(R.layout.user_edit);
		
	// INSTANCIRANJE OBJEKTA
		
    	editName = (EditText) findViewById(R.id.userEditEditName);
    	editSurname = (EditText) findViewById(R.id.userEditEditSurname);
    	editDate = (EditText) findViewById(R.id.userEditEditDate);
    	editEmail = (EditText) findViewById(R.id.userEditEditEmail);
    	editPassword = (EditText) findViewById(R.id.userEditEditPassword);
    	editPasswordRepeat = (EditText) findViewById(R.id.userEditEditPasswordRepeat);
    	labelPassword = (TextView) findViewById(R.id.userEditLabelPassword);
    	labelPasswordRepeat = (TextView) findViewById(R.id.userEditLabelPasswordRepeat);
    	btnSave = (Button) findViewById(R.id.userEditButtonSave);
    	image = (ImageView) findViewById(R.id.userEditImage);
    	intentResult = new Intent();
    	intentImage = new Intent();
    	intentImage.setType("image/*");
    	intentImage.setAction(Intent.ACTION_GET_CONTENT);
    	
    // AKCIJE NA STARTU
    	
    	userId = getIntent().getExtras().getLong("userId");
    	userInfoId = getIntent().getExtras().getLong("userInfoId");
    	    	
    	if (userId == 0) {
    		btnSave.setText("Create new account");
    	}
    	else if (userId == userInfoId) {
        	getProfileInfo();
    		btnSave.setText("Save changes");
    		labelPassword.setText("Old password");
    		labelPasswordRepeat.setText("New password");
    	}
    	else {
        	getProfileInfo();
    		editName.setFocusable(false);
    		editSurname.setFocusable(false);
    		editDate.setFocusable(false);
    		editEmail.setFocusable(false);
    		editPassword.setFocusable(false);
    		editPassword.setEnabled(false);
    		editPasswordRepeat.setFocusable(false);
    		editPasswordRepeat.setEnabled(false);    		
    		btnSave.setText("Exit");
    	}
    	
    	setResult(C.ERROR);
    	
    	// Klik na editDate ne povlaci virtualnu tipkovnicu 
    	editDate.setFocusable(false);
    	
        // Na editDate postavi danasnji datum
        final Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);
        updateDateDisplay();
        
	// EVENT LISTENERS
		
		btnSave.setOnClickListener( new OnClickListener() {
			public void onClick(View v) {
	        	if (userId == 0) {
	        		registerNewAccount();
	        	}
	        	else if (userId == userInfoId) {
	        		saveChanges();
	        	}
	        	else {
	        		finish();
	        	}
			}
		});
		
    	editDate.setOnClickListener( new OnClickListener() {
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});

    	image.setOnClickListener( new OnClickListener() {
			public void onClick(View v) {
				startActivityForResult(intentImage, 1);
			}
		});
	}
	
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this,mDateSetListener,year, month, day);
        }
        return null;
    }
    
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    	switch(requestCode) {
    	case 1:
    		C.toast(this, data.getDataString());
    		break;
    	}
    }
    
/* ********************** PRIVATE FUNCTIONS *******************************/

    private void updateDateDisplay() {
    	editDate.setText(year + "-" + (month+1) + "-" + day);
    }
    
    private void saveChanges() {

    	String name, surname, date, oldPassword, newPassword, oldPasswordHash, newPasswordHash, email;
    	name = editName.getText().toString();
    	surname = editSurname.getText().toString();
    	date = editDate.getText().toString();
    	email = editEmail.getText().toString();
    	oldPassword = editPassword.getText().toString();
    	newPassword = editPasswordRepeat.getText().toString();
    	                            
        int tmp=0;
        String message = getString(R.string.toastRegisterEmptyEntries);
            
        if (name.isEmpty())  { message += "\nName"; tmp++; }
        if (surname.isEmpty()){ message += "\nSurname";  tmp++; }
        if (email.isEmpty()){ message += "\nEmail";  tmp++; }
        if (date.isEmpty()){ message += "\nDate";  tmp++; }
        if (oldPassword.isEmpty()){ message += "\nOld password";  tmp++; }
        if (newPassword.isEmpty()){ message +="\nNew password";  tmp++; } 
        if (tmp > 0) {
        	C.toast(this, message);
        	return;
        }
        
        newPasswordHash = C.SHA1.compute(newPassword);
        if (newPasswordHash.length() != 40) {
        	C.toast(this, R.string.toastPasswordHashError);
        	return;
        }
        
        oldPasswordHash = C.SHA1.compute(oldPassword);
        if (oldPasswordHash.length() != 40) {
        	C.toast(this, R.string.toastPasswordHashError);
        	return;
        }
        
        RestClient client = new RestClient(getString(R.string.serverMethodEditProfileInfo));
        
        client.AddParam("userId", String.valueOf(userId));
        client.AddParam("name", name);
        client.AddParam("surname", surname);
        client.AddParam("date", date);
        client.AddParam("email", email);
        client.AddParam("passwordOld", oldPasswordHash);
        client.AddParam("passwordNew", newPasswordHash);
        
        String result = C.getMethod0(client,getString(R.string.serverMethodEditProfileInfo)); 
        
        if (C.resultSuccess(this, result, getString(R.string.toastEditProfileInfoError))) {
        	finish();
        }
    }
    
    private void getProfileInfo() {
    	Log.d(C.TAG, "USER EDIT: getProfileInfo()");
    	RestClient client = new RestClient(getString(R.string.serverMethodGetProfileInfo));
    	client.AddParam("userId", String.valueOf(userInfoId));
    	
    	String result[] = C.getMethod1 (client,getString(R.string.serverMethodGetProfileInfo));
    	
    	if (C.resultSuccess(this, result, getString(R.string.toastCircleEditError))) {
			editName.setText(result[0]);
			editSurname.setText(result[1]);
			editDate.setText(result[2]);
			editEmail.setText(result[3]);
    	}

    }
    
    private void registerNewAccount() {
    	Log.d(C.TAG, "REGISTER: registerNewAccount()");
    	
    	String name, surname, date, password, passwordRepeat, passwordHash, email;
    	name = editName.getText().toString();
    	surname = editSurname.getText().toString();
    	date = editDate.getText().toString();
    	email = editEmail.getText().toString();
    	password= editPassword.getText().toString();
    	passwordRepeat = editPasswordRepeat.getText().toString();
    	                
        // TODO VALIDACIJA PODATAKA - provjera emaila, prvo veliko slovo na imenu
            
        int tmp=0;
        String message = getString(R.string.toastRegisterEmptyEntries);
            
        if (name.isEmpty())  { message += "\nName"; tmp++; }
        if (surname.isEmpty()){ message += "\nSurname";  tmp++; }
        if (email.isEmpty()){ message += "\nEmail";  tmp++; }
        if (date.isEmpty()){ message += "\nDate";  tmp++; }
        if (password.isEmpty()){ message += "\nPassword";  tmp++; }
        if (passwordRepeat.isEmpty()){ message +="\nPassword repeat";  tmp++; } 
        if (tmp > 0) {
        	C.toast(this, message);
        	return;
        }
        
        if (password.compareTo(passwordRepeat) != 0) {
        	C.toast(this, R.string.toastRegisterPasswordsDontMatch);
        	return;
        }
        
        passwordHash = C.SHA1.compute(password);
        if (passwordHash.length() != 40) {
        	C.toast(this, R.string.toastPasswordHashError);
        	return;
        }
        
        RestClient client = new RestClient(getString(R.string.serverMethodRegister));
        client.AddParam("name", name);
        client.AddParam("surname", surname);
        client.AddParam("date", date);
        client.AddParam("email", email);
        client.AddParam("password", passwordHash);
        
        String result = C.getMethod0(client,getString(R.string.serverMethodRegister));            
        
        if (C.resultSuccess(this, result, getString(R.string.toastRegisterServerError))) {
            long userId = Integer.parseInt(result);
            if (userId <= 0) {
            	C.toast(this,R.string.toastRegisterServerError);
            }
            else {
            	intentResult.putExtra("email", email);
            	intentResult.putExtra("password", password);
                setResult(C.SUCCESS, intentResult);
                finish();
            }
        }
    }
}
